<template>
  <div>
    <!-- <el-row>
        <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
      </el-row> -->
    <el-row>
      <el-col style="float:left;width:560px;margin-bottom:10px;background-color:#f2f2f2;">
        <el-button type="text" style="color: #606266;">机油格</el-button>
        <el-button size="small" type="primary" style="float:right;" :loading="exportLoading" @click="requestExportData">导出</el-button>
        <el-button size="small" type="primary" style="float:right;" @click="addFun('1')">新增</el-button>
      </el-col>
      <el-col style="float:right;width:560px;margin-bottom:10px;background-color:#f2f2f2;">
        <el-button type="text" style="color: #606266;">保养规则二采用机油</el-button>
        <el-button size="small" type="primary" style="float:right;" :loading="exportLoading" @click="requestExportData_two">导出</el-button>
        <el-button size="small" type="primary" style="float:right;" @click="addFun('2')">新增</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col style="float:left;width:560px;">
        <FilterTable
          ref="table"
          columnsRef="partInventoryManagerPartInformationIndex"
          :isSelectColumn="false"
          :dataSource="dataSourceList1"
          :columns="columns"
          :fetchapi="fetchApi"
          :datakey="'rows'"
          :params="fetchParams"
          height="380"
          :onColumnsChange="columns => (this.columns = columns)"
        >
        </FilterTable>
      </el-col>
      <!-- //第二个表格 -->
      <el-col style="float:right;width:560px;">
        <FilterTable
          ref="tables"
          columnsRef="partInventoryManagerPartInformationIndex1"
          :isSelectColumn="false"
          :dataSource="dataSourceList2"
          :columns="columns2"
          :fetchapi="fetchApis"
          :datakey="'rows'"
          :params="fetchParams"
          height="380"
          :onColumnsChange="columns => (this.columns2 = columns)"
        >
        </FilterTable>
      </el-col>
    </el-row>
    <el-row style="text-align: center;margin-top:10px;margin-bottom:10px;">
      <el-button size="small" type="primary" icon="el-icon-folder" :disabled="once" @click="changeSave">保存</el-button>
      <el-button size="small" type="primary" icon="el-icon-refresh-left" @click="changeCz">重置</el-button>
    </el-row>
    <!-- <template slot="controls" slot-scope="props">
            <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
            <el-button size="small">下载</el-button>
            <el-button size="small">导入</el-button>
          </template> -->

    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      destroyOnClose
      :width="900"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @afterVisibleChange="afterVisibleChangeHandle"
    >
      <editPage :handleType="handleType" :rowData="formData" @close="closeHandler" @datalistOne="datalistOne" @datalistTwo="datalistTwo" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getPartsInformation, getExcelList, getExcelList_two } from '@/api/part/inventoryManager/partInformation';
import { getPartsInformations } from '@/api/part/inventoryManager/partInformation';
import { getAllBrand } from '@/api/part/inventoryManager/partInformation';
import { getAllModel } from '@/api/part/inventoryManager/partInformation';
import { delPartById } from '@/api/part/inventoryManager/partInformation';
import { exportExcelFile } from '@/utils/index';
import editPage from './addPart';
import { addPart } from '@/api/part/inventoryManager/partInformation';
export default {
  name: 'partInformation',
  components: {
    editPage
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      once: true,
      pd1: true,
      pd2: true,
      dataSourceList1: [],
      dataSourceList2: [],
      topFilterList: this.createTopFilterList(),
      fetchParams: { pageNum: 1, xhrAbort: false },
      visible: false,
      dialogTitle: '',
      fetchApi: getPartsInformations,
      fetchApis: getPartsInformation,
      columns2: this.createTableColumns2(),
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      dataSource: []
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName'
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择...',
          initialValue: '',
          request: {
            fetchApi: getAllBrand,
            params: {},
            datekey: '',
            valueKey: 'BRAND',
            textKey: 'BRAND'
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'PART_VEHICLE_MODEL',
          placeholder: '请选择...',
          initialValue: '',
          request: {
            fetchApi: getAllModel,
            params: {},
            datekey: '',
            valueKey: 'PART_VEHICLE_MODEL',
            textKey: 'PART_VEHICLE_MODEL'
          }
        },
        {
          type: 'SELECT',
          label: 'OEG下发',
          fieldName: 'oemNo',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否有效',
          fieldName: 'IS_FREEZE',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 89,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.beforeDelete(props.row, '1')}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          width: 100,
          sorter: true
          // filter: true,
          // filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          width: 100,
          sorter: true
        },
        {
          title: '数据来源',
          dataIndex: 'OEM_TAG',
          render: props => {
            return <span>{this.createDictText(props.row.OEM_TAG, 1045)}</span>;
          },
          width: 100
        },
        {
          title: '是否有效',
          dataIndex: 'IS_FREEZE',
          render: props => {
            return <span>{this.createDictText(props.row.IS_FREEZE, 1004)}</span>;
          },
          width: 100
        }
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 89,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.beforeDelete(props.row, '2')}>
                  删除
                </el-button>
              </div>
            );
            // disabled={props.row.OEM_TAG === 10451002 ? true : false}
          }
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          width: 100,
          sorter: true
          // filter: true,
          // filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          width: 100,
          sorter: true
        },
        {
          title: '数据来源',
          dataIndex: 'OEM_TAG',
          render: props => {
            return <span>{this.createDictText(props.row.OEM_TAG, 1045)}</span>;
          },
          width: 100
        },
        {
          title: '是否有效',
          dataIndex: 'IS_FREEZE',
          render: props => {
            return <span>{this.createDictText(props.row.IS_FREEZE, 1004)}</span>;
          },
          width: 100
        }
      ];
    },
    datalistOne(val) {
      this.pd1 = true;
      let pdone = true;
      let pdtwo = true;
      this.dataSourceList1.forEach(x => {
        val.forEach(item => {
          if (x.PART_NO == item.PART_NO) {
            pdone = false;
          }
          if ((x.PART_NAME = item.PART_NAME)) {
            pdtwo = false;
          }
          if (pdone == false && pdtwo == false) {
            this.pd1 = false;
          }
        });
      });
      if (this.pd1) {
        if (this.once) {
          this.dataSourceList1 = [];
          this.dataSourceList2 = [];
        }
        this.once = false;
        console.log(val, 'val');
        val.forEach(x => {
          this.dataSourceList1.push(x);
        });
        //  this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
      } else {
        this.$notify({
          title: '警告',
          message: '添加的配件已存在',
          type: 'warning'
        });
      }
    },
    datalistTwo(val) {
      this.pd2 = true;
      let pdone = true;
      let pdtwo = true;
      this.dataSourceList2.forEach(x => {
        val.forEach(item => {
          if (x.PART_NO == item.PART_NO) {
            pdone = false;
          }
          if ((x.PART_NAME = item.PART_NAME)) {
            pdtwo = false;
          }
          if (pdone == false && pdtwo == false) {
            this.pd2 = false;
          }
        });
      });
      if (this.pd2) {
        if (this.once) {
          this.dataSourceList1 = [];
          this.dataSourceList2 = [];
        }
        this.once = false;
        val.forEach(x => {
          this.dataSourceList2.push(x);
        });
        //  this.$refs.tables.$refs.pageTable.EXECUTE_INSERT(val);
      } else {
        this.$notify({
          title: '警告',
          message: '添加的配件已存在',
          type: 'warning'
        });
      }
    },

    /* 机油格导出 */
    requestExportData() {
      this.exportLoading = true;
      const option = {};
      getExcelList(this.fetchParams).then(response => {
        console.log(response, '机油主数据');
        exportExcelFile(response.data, '机油主数据');
        this.exportLoading = false;
        // this.exportExcel(res.records);
      });
    },
    // exportModelExcel() {
    //   const option = {
    //     tHeader: ['配件代码', '配件名称', '数据来源', '是否有效'],
    //     filterVal: ['PART_NO', 'PART_NAME', 'OEM_TAG', 'IS_VALID'],
    //     fileName: '机油信息模板'
    //   };
    //   exportFile(option, () => {
    //     this.exportLoading = false;
    //   });
    // },
    /* 保养规则二采用机油 */
    requestExportData_two() {
      this.exportLoading = true;
      const option = {};
      getExcelList_two(this.fetchParams).then(response => {
        exportExcelFile(response.data, '保养规则二采用机油主数据');
        this.exportLoading = false;
      });
    },
    exportModelExcel() {
      const option = {
        tHeader: ['配件代码', '配件名称', '数据来源', '是否有效'],
        filterVal: ['PART_NO', 'PART_NAME', 'OEM_TAG', 'IS_VALID'],
        fileName: '保养规则二采用机油信息模板'
      };
      exportFile(option, () => {
        this.exportLoading = false;
      });
    },
    /* 保存按钮 */
    changeSave() {
      this.dataSourceList1.forEach(x => {
        x.PART_TYPE = '80461002';
      });
      this.dataSourceList2.forEach(x => {
        x.PART_TYPE = '80461001';
      });
      let newArr = this.dataSourceList1.concat(this.dataSourceList2);
      this.addPart(newArr);
    },
    /* 添加请求 */
    async addPart(row) {
      let res = await addPart(row);
      if (res.resultCode == '200') {
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        this.once = true;
        this.fetchParams = { xhrAbort: false };
      }
    },
    /* 重置按钮 */
    changeCz() {
      // this.dataSourceList1 = []
      // this.dataSourceList2 = []
      this.fetchParams = { xhrAbort: false };
      this.once = true;
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    /* 新增 */
    addFun(val) {
      this.handleType = val;
      this.dialogTitle = `保养配件新增`;
      this.visible = true;
    },
    /* 删除 */
    beforeDelete(row, type) {
      console.log(row, 'dataSource');
      if (type == '1') {
        this.dataSourceList1.splice(row.index, 1);
      } else {
        this.dataSourceList2.splice(row.index, 1);
      }
      const No = row.PART_NO;
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delete(No);
        })
        .catch(() => {});
    },
    async delete(delPartNo) {
      let res = await delPartById(delPartNo);
      if (res.data == 1) {
        this.$notify.success({ title: '提示信息', message: res.errMsg || '删除成功!' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
      }
      this.fetchParams = { ...this.fetchParams };
    },
    /* 表单的参数 */
    changeHandle(val) {},
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.visible = true;
    },
    closeHandler() {
      this.visible = false;
    },
    afterVisibleChangeHandle(val) {
      if (val == false) {
        // this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>
<style lang="less" scoped></style>
